package com.ls.login;

import com.ls.common.ResultObj;
import com.ls.common.shiro.ActiverUser;
import com.ls.common.utils.WebUtils;
import com.ls.system.entity.SysUser;
import com.ls.system.service.SysUserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.crypto.SecureRandomNumberGenerator;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.Date;

/**
 * @Author lisheng
 * @Date 2025/04/06 22:04
 **/
@Controller
public class RedirectController {

    @GetMapping("/{url}")
    public String url(@PathVariable("url") String url){
        if(url.equals("")) url = "index";
        return url;
    }

    @GetMapping("favicon.ico")
    @ResponseBody
    void returnNoFavicon() {
    }

    @PostMapping("/login")
    @ResponseBody
    public ResultObj login(String loginname, String password){
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(loginname,password);
        try {
            subject.login(token);
            ActiverUser activerUser = (ActiverUser) subject.getPrincipal();
            WebUtils.getSession().setAttribute("user", activerUser.getUser());
            return ResultObj.LOGIN_SUCCESS;
        } catch (UnknownAccountException e) {
            return ResultObj.LOGIN_ERROR_LOGINNAME;
        } catch (IncorrectCredentialsException e) {
            return ResultObj.LOGIN_ERROR_PASS;
        }
    }

    @GetMapping("/logout")
    public String logout(){
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return "login";
    }

}